// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers.  See the top-level LICENSE file for dates and other
// details.  No copyright assignment is required to contribute to VisIt.

#include <PyLightAttributes.h>
#include <ObserverToCallback.h>
#include <stdio.h>
#include <Py2and3Support.h>
#include <ColorAttribute.h>

// ****************************************************************************
// Module: PyLightAttributes
//
// Purpose:
//   This class is a light in a light list.
//
// Note:       Autogenerated by xml2python. Do not modify by hand!
//
// Programmer: xml2python
// Creation:   omitted
//
// ****************************************************************************

//
// This struct contains the Python type information and a LightAttributes.
//
struct LightAttributesObject
{
    PyObject_HEAD
    LightAttributes *data;
    bool        owns;
    PyObject   *parent;
};

//
// Internal prototypes
//
static PyObject *NewLightAttributes(int);
std::string
PyLightAttributes_ToString(const LightAttributes *atts, const char *prefix, const bool forLogging)
{
    std::string str;
    char tmpStr[1000];

    if(atts->GetEnabledFlag())
        snprintf(tmpStr, 1000, "%senabledFlag = 1\n", prefix);
    else
        snprintf(tmpStr, 1000, "%senabledFlag = 0\n", prefix);
    str += tmpStr;
    const char *type_names = "Ambient, Object, Camera";
    switch (atts->GetType())
    {
      case LightAttributes::Ambient:
          snprintf(tmpStr, 1000, "%stype = %sAmbient  # %s\n", prefix, prefix, type_names);
          str += tmpStr;
          break;
      case LightAttributes::Object:
          snprintf(tmpStr, 1000, "%stype = %sObject  # %s\n", prefix, prefix, type_names);
          str += tmpStr;
          break;
      case LightAttributes::Camera:
          snprintf(tmpStr, 1000, "%stype = %sCamera  # %s\n", prefix, prefix, type_names);
          str += tmpStr;
          break;
      default:
          break;
    }

    {   const double *direction = atts->GetDirection();
        snprintf(tmpStr, 1000, "%sdirection = (", prefix);
        str += tmpStr;
        for(int i = 0; i < 3; ++i)
        {
            snprintf(tmpStr, 1000, "%g", direction[i]);
            str += tmpStr;
            if(i < 2)
            {
                snprintf(tmpStr, 1000, ", ");
                str += tmpStr;
            }
        }
        snprintf(tmpStr, 1000, ")\n");
        str += tmpStr;
    }
    const unsigned char *color = atts->GetColor().GetColor();
    snprintf(tmpStr, 1000, "%scolor = (%d, %d, %d, %d)\n", prefix, int(color[0]), int(color[1]), int(color[2]), int(color[3]));
    str += tmpStr;
    snprintf(tmpStr, 1000, "%sbrightness = %g\n", prefix, atts->GetBrightness());
    str += tmpStr;
    return str;
}

static PyObject *
LightAttributes_Notify(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;
    obj->data->Notify();
    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
LightAttributes_SetEnabledFlag(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;

    PyObject *packaged_args = 0;

    // Handle args packaged into a tuple of size one
    // if we think the unpackaged args matches our needs
    if (PySequence_Check(args) && PySequence_Size(args) == 1)
    {
        packaged_args = PySequence_GetItem(args, 0);
        if (PyNumber_Check(packaged_args))
            args = packaged_args;
    }

    if (PySequence_Check(args))
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_TypeError, "expecting a single number arg");
    }

    if (!PyNumber_Check(args))
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_TypeError, "arg is not a number type");
    }

    long val = PyLong_AsLong(args);
    bool cval = bool(val);

    if (val == -1 && PyErr_Occurred())
    {
        Py_XDECREF(packaged_args);
        PyErr_Clear();
        return PyErr_Format(PyExc_TypeError, "arg not interpretable as C++ bool");
    }
    if (fabs(double(val))>1.5E-7 && fabs((double(long(cval))-double(val))/double(val))>1.5E-7)
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_ValueError, "arg not interpretable as C++ bool");
    }

    Py_XDECREF(packaged_args);

    // Set the enabledFlag in the object.
    obj->data->SetEnabledFlag(cval);

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
LightAttributes_GetEnabledFlag(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;
    PyObject *retval = PyInt_FromLong(obj->data->GetEnabledFlag()?1L:0L);
    return retval;
}

/*static*/ PyObject *
LightAttributes_SetType(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;

    PyObject *packaged_args = 0;

    // Handle args packaged into a tuple of size one
    // if we think the unpackaged args matches our needs
    if (PySequence_Check(args) && PySequence_Size(args) == 1)
    {
        packaged_args = PySequence_GetItem(args, 0);
        if (PyNumber_Check(packaged_args))
            args = packaged_args;
    }

    if (PySequence_Check(args))
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_TypeError, "expecting a single number arg");
    }

    if (!PyNumber_Check(args))
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_TypeError, "arg is not a number type");
    }

    long val = PyLong_AsLong(args);
    int cval = int(val);

    if ((val == -1 && PyErr_Occurred()) || long(cval) != val)
    {
        Py_XDECREF(packaged_args);
        PyErr_Clear();
        return PyErr_Format(PyExc_TypeError, "arg not interpretable as C++ int");
    }

    if (cval < 0 || cval >= 3)
    {
        std::stringstream ss;
        ss << "An invalid type value was given." << std::endl;
        ss << "Valid values are in the range [0,2]." << std::endl;
        ss << "You can also use the following symbolic names:";
        ss << " Ambient";
        ss << ", Object";
        ss << ", Camera";
        return PyErr_Format(PyExc_ValueError, ss.str().c_str());
    }

    Py_XDECREF(packaged_args);

    // Set the type in the object.
    obj->data->SetType(LightAttributes::LightType(cval));

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
LightAttributes_GetType(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;
    PyObject *retval = PyInt_FromLong(long(obj->data->GetType()));
    return retval;
}

/*static*/ PyObject *
LightAttributes_SetDirection(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;

    PyObject *packaged_args = 0;
    double *vals = obj->data->GetDirection();

    if (!PySequence_Check(args) || PyUnicode_Check(args))
        return PyErr_Format(PyExc_TypeError, "Expecting a sequence of numeric args");

    // break open args seq. if we think it matches this API's needs
    if (PySequence_Size(args) == 1)
    {
        packaged_args = PySequence_GetItem(args, 0);
        if (PySequence_Check(packaged_args) && !PyUnicode_Check(packaged_args) &&
            PySequence_Size(packaged_args) == 3)
            args = packaged_args;
    }

    if (PySequence_Size(args) != 3)
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_TypeError, "Expecting 3 numeric args");
    }

    for (Py_ssize_t i = 0; i < PySequence_Size(args); i++)
    {
        PyObject *item = PySequence_GetItem(args, i);

        if (!PyNumber_Check(item))
        {
            Py_DECREF(item);
            Py_XDECREF(packaged_args);
            return PyErr_Format(PyExc_TypeError, "arg %d is not a number type", (int) i);
        }

        double val = PyFloat_AsDouble(item);
        double cval = double(val);

        if (val == -1 && PyErr_Occurred())
        {
            Py_XDECREF(packaged_args);
            Py_DECREF(item);
            PyErr_Clear();
            return PyErr_Format(PyExc_TypeError, "arg %d not interpretable as C++ double", (int) i);
        }
        if (fabs(double(val))>1.5E-7 && fabs((double(double(cval))-double(val))/double(val))>1.5E-7)
        {
            Py_XDECREF(packaged_args);
            Py_DECREF(item);
            return PyErr_Format(PyExc_ValueError, "arg %d not interpretable as C++ double", (int) i);
        }
        Py_DECREF(item);

        vals[i] = cval;
    }

    Py_XDECREF(packaged_args);

    // Mark the direction in the object as modified.
    obj->data->SelectDirection();

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
LightAttributes_GetDirection(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;
    // Allocate a tuple the with enough entries to hold the direction.
    PyObject *retval = PyTuple_New(3);
    const double *direction = obj->data->GetDirection();
    for(int i = 0; i < 3; ++i)
        PyTuple_SET_ITEM(retval, i, PyFloat_FromDouble(direction[i]));
    return retval;
}

/*static*/ PyObject *
LightAttributes_SetColor(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;

    int c[4];
    if(!PyArg_ParseTuple(args, "iiii", &c[0], &c[1], &c[2], &c[3]))
    {
        c[3] = 255;
        if(!PyArg_ParseTuple(args, "iii", &c[0], &c[1], &c[2]))
        {
            double dr, dg, db, da;
            if(PyArg_ParseTuple(args, "dddd", &dr, &dg, &db, &da))
            {
                c[0] = int(dr);
                c[1] = int(dg);
                c[2] = int(db);
                c[3] = int(da);
            }
            else if(PyArg_ParseTuple(args, "ddd", &dr, &dg, &db))
            {
                c[0] = int(dr);
                c[1] = int(dg);
                c[2] = int(db);
                c[3] = 255;
            }
            else
            {
                PyObject *tuple = NULL;
                if(!PyArg_ParseTuple(args, "O", &tuple))
                    return NULL;

                if(!PyTuple_Check(tuple))
                    return NULL;

                // Make sure that the tuple is the right size.
                if(PyTuple_Size(tuple) < 3 || PyTuple_Size(tuple) > 4)
                    return NULL;

                // Make sure that all elements in the tuple are ints.
                for(int i = 0; i < PyTuple_Size(tuple); ++i)
                {
                    PyObject *item = PyTuple_GET_ITEM(tuple, i);
                    if(PyInt_Check(item))
                        c[i] = int(PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, i)));
                    else if(PyFloat_Check(item))
                        c[i] = int(PyFloat_AS_DOUBLE(PyTuple_GET_ITEM(tuple, i)));
                    else
                        return NULL;
                }
            }
        }
        PyErr_Clear();
    }

    // Set the color in the object.
    ColorAttribute ca(c[0], c[1], c[2], c[3]);
    obj->data->SetColor(ca);

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
LightAttributes_GetColor(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;
    // Allocate a tuple the with enough entries to hold the color.
    PyObject *retval = PyTuple_New(4);
    const unsigned char *color = obj->data->GetColor().GetColor();
    PyTuple_SET_ITEM(retval, 0, PyInt_FromLong(long(color[0])));
    PyTuple_SET_ITEM(retval, 1, PyInt_FromLong(long(color[1])));
    PyTuple_SET_ITEM(retval, 2, PyInt_FromLong(long(color[2])));
    PyTuple_SET_ITEM(retval, 3, PyInt_FromLong(long(color[3])));
    return retval;
}

/*static*/ PyObject *
LightAttributes_SetBrightness(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;

    PyObject *packaged_args = 0;

    // Handle args packaged into a tuple of size one
    // if we think the unpackaged args matches our needs
    if (PySequence_Check(args) && PySequence_Size(args) == 1)
    {
        packaged_args = PySequence_GetItem(args, 0);
        if (PyNumber_Check(packaged_args))
            args = packaged_args;
    }

    if (PySequence_Check(args))
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_TypeError, "expecting a single number arg");
    }

    if (!PyNumber_Check(args))
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_TypeError, "arg is not a number type");
    }

    double val = PyFloat_AsDouble(args);
    double cval = double(val);

    if (val == -1 && PyErr_Occurred())
    {
        Py_XDECREF(packaged_args);
        PyErr_Clear();
        return PyErr_Format(PyExc_TypeError, "arg not interpretable as C++ double");
    }
    if (fabs(double(val))>1.5E-7 && fabs((double(double(cval))-double(val))/double(val))>1.5E-7)
    {
        Py_XDECREF(packaged_args);
        return PyErr_Format(PyExc_ValueError, "arg not interpretable as C++ double");
    }

    Py_XDECREF(packaged_args);

    // Set the brightness in the object.
    obj->data->SetBrightness(cval);

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
LightAttributes_GetBrightness(PyObject *self, PyObject *args)
{
    LightAttributesObject *obj = (LightAttributesObject *)self;
    PyObject *retval = PyFloat_FromDouble(obj->data->GetBrightness());
    return retval;
}



PyMethodDef PyLightAttributes_methods[LIGHTATTRIBUTES_NMETH] = {
    {"Notify", LightAttributes_Notify, METH_VARARGS},
    {"SetEnabledFlag", LightAttributes_SetEnabledFlag, METH_VARARGS},
    {"GetEnabledFlag", LightAttributes_GetEnabledFlag, METH_VARARGS},
    {"SetType", LightAttributes_SetType, METH_VARARGS},
    {"GetType", LightAttributes_GetType, METH_VARARGS},
    {"SetDirection", LightAttributes_SetDirection, METH_VARARGS},
    {"GetDirection", LightAttributes_GetDirection, METH_VARARGS},
    {"SetColor", LightAttributes_SetColor, METH_VARARGS},
    {"GetColor", LightAttributes_GetColor, METH_VARARGS},
    {"SetBrightness", LightAttributes_SetBrightness, METH_VARARGS},
    {"GetBrightness", LightAttributes_GetBrightness, METH_VARARGS},
    {NULL, NULL}
};

//
// Type functions
//

static void
LightAttributes_dealloc(PyObject *v)
{
   LightAttributesObject *obj = (LightAttributesObject *)v;
   if(obj->parent != 0)
       Py_DECREF(obj->parent);
   if(obj->owns)
       delete obj->data;
}

static PyObject *LightAttributes_richcompare(PyObject *self, PyObject *other, int op);
PyObject *
PyLightAttributes_getattr(PyObject *self, char *name)
{
    if(strcmp(name, "enabledFlag") == 0)
        return LightAttributes_GetEnabledFlag(self, NULL);
    if(strcmp(name, "type") == 0)
        return LightAttributes_GetType(self, NULL);
    if(strcmp(name, "Ambient") == 0)
        return PyInt_FromLong(long(LightAttributes::Ambient));
    if(strcmp(name, "Object") == 0)
        return PyInt_FromLong(long(LightAttributes::Object));
    if(strcmp(name, "Camera") == 0)
        return PyInt_FromLong(long(LightAttributes::Camera));

    if(strcmp(name, "direction") == 0)
        return LightAttributes_GetDirection(self, NULL);
    if(strcmp(name, "color") == 0)
        return LightAttributes_GetColor(self, NULL);
    if(strcmp(name, "brightness") == 0)
        return LightAttributes_GetBrightness(self, NULL);


    // Add a __dict__ answer so that dir() works
    if (!strcmp(name, "__dict__"))
    {
        PyObject *result = PyDict_New();
        for (int i = 0; PyLightAttributes_methods[i].ml_meth; i++)
            PyDict_SetItem(result,
                PyString_FromString(PyLightAttributes_methods[i].ml_name),
                PyString_FromString(PyLightAttributes_methods[i].ml_name));
        return result;
    }

    return Py_FindMethod(PyLightAttributes_methods, self, name);
}

int
PyLightAttributes_setattr(PyObject *self, char *name, PyObject *args)
{
    PyObject NULL_PY_OBJ;
    PyObject *obj = &NULL_PY_OBJ;

    if(strcmp(name, "enabledFlag") == 0)
        obj = LightAttributes_SetEnabledFlag(self, args);
    else if(strcmp(name, "type") == 0)
        obj = LightAttributes_SetType(self, args);
    else if(strcmp(name, "direction") == 0)
        obj = LightAttributes_SetDirection(self, args);
    else if(strcmp(name, "color") == 0)
        obj = LightAttributes_SetColor(self, args);
    else if(strcmp(name, "brightness") == 0)
        obj = LightAttributes_SetBrightness(self, args);

    if (obj != NULL && obj != &NULL_PY_OBJ)
        Py_DECREF(obj);

    if (obj == &NULL_PY_OBJ)
    {
        obj = NULL;
        PyErr_Format(PyExc_NameError, "name '%s' is not defined", name);
    }
    else if (obj == NULL && !PyErr_Occurred())
        PyErr_Format(PyExc_RuntimeError, "unknown problem with '%s'", name);

    return (obj != NULL) ? 0 : -1;
}

static int
LightAttributes_print(PyObject *v, FILE *fp, int flags)
{
    LightAttributesObject *obj = (LightAttributesObject *)v;
    fprintf(fp, "%s", PyLightAttributes_ToString(obj->data, "",false).c_str());
    return 0;
}

PyObject *
LightAttributes_str(PyObject *v)
{
    LightAttributesObject *obj = (LightAttributesObject *)v;
    return PyString_FromString(PyLightAttributes_ToString(obj->data,"", false).c_str());
}

//
// The doc string for the class.
//
#if PY_MAJOR_VERSION > 2 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 5)
static const char *LightAttributes_Purpose = "This class is a light in a light list.";
#else
static char *LightAttributes_Purpose = "This class is a light in a light list.";
#endif

//
// Python Type Struct Def Macro from Py2and3Support.h
//
//         VISIT_PY_TYPE_OBJ( VPY_TYPE,
//                            VPY_NAME,
//                            VPY_OBJECT,
//                            VPY_DEALLOC,
//                            VPY_PRINT,
//                            VPY_GETATTR,
//                            VPY_SETATTR,
//                            VPY_STR,
//                            VPY_PURPOSE,
//                            VPY_RICHCOMP,
//                            VPY_AS_NUMBER)

//
// The type description structure
//

VISIT_PY_TYPE_OBJ(LightAttributesType,         \
                  "LightAttributes",           \
                  LightAttributesObject,       \
                  LightAttributes_dealloc,     \
                  LightAttributes_print,       \
                  PyLightAttributes_getattr,   \
                  PyLightAttributes_setattr,   \
                  LightAttributes_str,         \
                  LightAttributes_Purpose,     \
                  LightAttributes_richcompare, \
                  0); /* as_number*/

//
// Helper function for comparing.
//
static PyObject *
LightAttributes_richcompare(PyObject *self, PyObject *other, int op)
{
    // only compare against the same type 
    if ( Py_TYPE(self) != &LightAttributesType
         || Py_TYPE(other) != &LightAttributesType)
    {
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }

    PyObject *res = NULL;
    LightAttributes *a = ((LightAttributesObject *)self)->data;
    LightAttributes *b = ((LightAttributesObject *)other)->data;

    switch (op)
    {
       case Py_EQ:
           res = (*a == *b) ? Py_True : Py_False;
           break;
       case Py_NE:
           res = (*a != *b) ? Py_True : Py_False;
           break;
       default:
           res = Py_NotImplemented;
           break;
    }

    Py_INCREF(res);
    return res;
}

//
// Helper functions for object allocation.
//

static LightAttributes *defaultAtts = 0;
static LightAttributes *currentAtts = 0;

static PyObject *
NewLightAttributes(int useCurrent)
{
    LightAttributesObject *newObject;
    newObject = PyObject_NEW(LightAttributesObject, &LightAttributesType);
    if(newObject == NULL)
        return NULL;
    if(useCurrent && currentAtts != 0)
        newObject->data = new LightAttributes(*currentAtts);
    else if(defaultAtts != 0)
        newObject->data = new LightAttributes(*defaultAtts);
    else
        newObject->data = new LightAttributes;
    newObject->owns = true;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

static PyObject *
WrapLightAttributes(const LightAttributes *attr)
{
    LightAttributesObject *newObject;
    newObject = PyObject_NEW(LightAttributesObject, &LightAttributesType);
    if(newObject == NULL)
        return NULL;
    newObject->data = (LightAttributes *)attr;
    newObject->owns = false;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

///////////////////////////////////////////////////////////////////////////////
//
// Interface that is exposed to the VisIt module.
//
///////////////////////////////////////////////////////////////////////////////

PyObject *
LightAttributes_new(PyObject *self, PyObject *args)
{
    int useCurrent = 0;
    if (!PyArg_ParseTuple(args, "i", &useCurrent))
    {
        if (!PyArg_ParseTuple(args, ""))
            return NULL;
        else
            PyErr_Clear();
    }

    return (PyObject *)NewLightAttributes(useCurrent);
}

//
// Plugin method table. These methods are added to the visitmodule's methods.
//
static PyMethodDef LightAttributesMethods[] = {
    {"LightAttributes", LightAttributes_new, METH_VARARGS},
    {NULL,      NULL}        /* Sentinel */
};

static Observer *LightAttributesObserver = 0;

std::string
PyLightAttributes_GetLogString()
{
    std::string s("LightAtts = LightAttributes()\n");
    if(currentAtts != 0)
        s += PyLightAttributes_ToString(currentAtts, "LightAtts.", true);
    return s;
}

static void
PyLightAttributes_CallLogRoutine(Subject *subj, void *data)
{
    typedef void (*logCallback)(const std::string &);
    logCallback cb = (logCallback)data;

    if(cb != 0)
    {
        std::string s("LightAtts = LightAttributes()\n");
        s += PyLightAttributes_ToString(currentAtts, "LightAtts.", true);
        cb(s);
    }
}

void
PyLightAttributes_StartUp(LightAttributes *subj, void *data)
{
    if(subj == 0)
        return;

    currentAtts = subj;
    PyLightAttributes_SetDefaults(subj);

    //
    // Create the observer that will be notified when the attributes change.
    //
    if(LightAttributesObserver == 0)
    {
        LightAttributesObserver = new ObserverToCallback(subj,
            PyLightAttributes_CallLogRoutine, (void *)data);
    }

}

void
PyLightAttributes_CloseDown()
{
    delete defaultAtts;
    defaultAtts = 0;
    delete LightAttributesObserver;
    LightAttributesObserver = 0;
}

PyMethodDef *
PyLightAttributes_GetMethodTable(int *nMethods)
{
    *nMethods = 1;
    return LightAttributesMethods;
}

bool
PyLightAttributes_Check(PyObject *obj)
{
    return (obj->ob_type == &LightAttributesType);
}

LightAttributes *
PyLightAttributes_FromPyObject(PyObject *obj)
{
    LightAttributesObject *obj2 = (LightAttributesObject *)obj;
    return obj2->data;
}

PyObject *
PyLightAttributes_New()
{
    return NewLightAttributes(0);
}

PyObject *
PyLightAttributes_Wrap(const LightAttributes *attr)
{
    return WrapLightAttributes(attr);
}

void
PyLightAttributes_SetParent(PyObject *obj, PyObject *parent)
{
    LightAttributesObject *obj2 = (LightAttributesObject *)obj;
    obj2->parent = parent;
}

void
PyLightAttributes_SetDefaults(const LightAttributes *atts)
{
    if(defaultAtts)
        delete defaultAtts;

    defaultAtts = new LightAttributes(*atts);
}

